package models

import (
	"github.com/beego/beego/v2/adapter/orm"
)

type SalesOrders struct {
	OrderID        int    `orm:"column(order_ID)"`
	OrderName      string `orm:"column(order_name)"`
	OrderStatus    int    `orm:"column(order_status)"`
	OrderStartTime string `orm:"column(order_start_time)"`
	OrderEndTime   string `orm:"column(order_end_time)"`
	OrderBreakTime string `orm:"column(order_break_time)"`
	ServiceID      int    `orm:"column(service_ID)"`
}

func init() {
	orm.RegisterModel(new(SalesOrders))
}

type OrderSimpleViewModel struct {
	OrderID        int     `json:"orderID" orm:"column(order_ID)"`
	OrderName      string  `json:"orderName" orm:"column(order_name)"`
	OrderStatus    int     `json:"orderStatus" orm:"column(order_status)"`
	OrderStartTime string  `json:"orderStartTime" orm:"column(order_start_time)"`
	OrderBudget    float32 `json:"orderBudget" orm:"column(order_budget)"`
}

// GetOrderListByServiceID 获得订单信息
func GetOrderListByServiceID(serviceID int) ([]OrderSimpleViewModel, int64) {
	o := orm.NewOrm()
	var orders []OrderSimpleViewModel
	num, err := o.Raw("select order_ID,order_name,order_status,order_start_time,order_budget from sales_orders where service_ID = ? order by order_status", serviceID).QueryRows(&orders)
	if err == nil {
		return orders, num
	} else {
		return []OrderSimpleViewModel{}, num
	}
}

type OrderSubmitModel struct {
	OrderName   string  `json:"orderName" orm:"column(order_name)"`
	OrderBudget float32 `json:"orderBudget" orm:"column(order_budget)"`
	ServiceID   int     `json:"serviceID" orm:"column(service_ID)"`
}

// AddOrder 添加订单
func AddOrder(submit OrderSubmitModel) error {
	o := orm.NewOrm()
	err := o.Begin()
	_, err = o.Raw("INSERT INTO sales_orders (order_name,order_budget,service_ID,order_start_time) VALUES (?, ?, ?, NOW())", submit.OrderName, submit.OrderBudget, submit.ServiceID).Exec()
	_, err = o.Raw("update services set service_status = 2 , service_budget = service_budget + ? where service_ID = ?", submit.OrderBudget, submit.ServiceID).Exec()
	if err != nil {
		err = o.Rollback()
		return err
	} else {
		err = o.Commit()
		return nil
	}
}
